package com.xk.sport.backend.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.xk.sport.backend.common.annotation.Login;
import com.xk.sport.backend.common.constant.ResultStatus;
import com.xk.sport.backend.common.entity.Result;
import com.xk.sport.backend.common.entity.TeacherQuery;
import com.xk.sport.backend.common.util.XlsUtil;
import com.xk.sport.backend.dao.model.Task;
import com.xk.sport.backend.dao.model.Teacher;
import com.xk.sport.backend.dao.repository.AreaDao;
import com.xk.sport.backend.dao.repository.LessonDao;
import com.xk.sport.backend.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Login
@Controller
@RequestMapping(value = "/teacher")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private AreaDao areaDao;
    @Autowired
    private LessonDao lessonDao;

    /**
     * 查询
     */
    @RequestMapping("/findAllByQueryAndPage")
    @ResponseBody
    public Result findAllByQueryAndPage(TeacherQuery query) {
        Page<Teacher> page = teacherService.findAllByQueryAndPage(query);
        return new Result(ResultStatus.success.getStatus(), "", page);
    }

    /**
     * 查询
     */
    @RequestMapping("/findOne")
    @ResponseBody
    public Result findOne(long id) {
        Teacher teacher = teacherService.findOne(id);
        return new Result(ResultStatus.success.getStatus(), "", teacher);
    }

    /**
     * 添加
     */
    @RequestMapping("/add")
    @ResponseBody
    public Result add(Teacher teacher) {
        Teacher newTeacher = teacherService.add(teacher);
        if (newTeacher != null) {
            return new Result(ResultStatus.success.getStatus(), "", newTeacher);
        } else {
            return new Result(ResultStatus.normal_error.getStatus(), "添加失败");
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public Result update(Teacher teacher) {
        if (teacher == null || teacher.getId() <= 0) {
            return new Result(ResultStatus.normal_error.getStatus(), "参数缺少teacherId");
        }
        Teacher newTeacher = teacherService.update(teacher);
        if (newTeacher != null) {
            return new Result(ResultStatus.success.getStatus(), "", newTeacher);
        } else {
            return new Result(ResultStatus.normal_error.getStatus(), "修改失败");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(long id) {
        if (teacherService.delete(id)) {
            return new Result(ResultStatus.success.getStatus(), "");
        } else {
            return new Result(ResultStatus.normal_error.getStatus(), "删除失败");
        }
    }

    /**
     * 上传
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(ResultStatus.normal_error.getStatus(), "文件为空");
        }
        String originalFileName = file.getOriginalFilename();
        if (Strings.isNullOrEmpty(originalFileName)) {
            return new Result(ResultStatus.normal_error.getStatus(), "文件名为空");
        }
        final List<Teacher> teachers = new ArrayList<>();
        int startrow = 0;
        int startcol = 0;
        XlsUtil.XlsErrorResult xlsErrorResult = XlsUtil.parseXls(file, startrow, startcol, (cellValue, i, j) -> {
            Teacher teacher = null;
            if (j == startcol) {
                teacher = new Teacher();
                teachers.add(teacher);
            } else {
                teacher = teachers.get(i - startrow);
            }
            cellValue = cellValue.trim();
            switch (j - startcol) {
                case 0:// 教师名对应name
                    teacher.setName(cellValue);
                    break;
                case 1:// 教师描述对应content
                    teacher.setContent(cellValue);
                    break;
                case 2:// 联系方式对应contact
                    teacher.setContact(cellValue);
                    break;
                case 3:// 社区对应areaId
                    Long[] areaIds = areaDao.findIdsByName(cellValue);
                    if (areaIds == null || areaIds.length <= 0) {
                        return new XlsUtil.XlsErrorResult(i, j, "地区名不存在");
                    }
                    long areaId = areaIds[0];
                    teacher.setAreaId(areaId);
                    break;
                case 4:// 课程列表对应lessonIds
                    List<Long> lessonIdList = new ArrayList<>();
                    String[] lessonNames = cellValue.split(",");
                    for (String lessonName : lessonNames) {
                        Long[] lessonIds = lessonDao.findIdsByName(lessonName);
                        if (lessonIds == null || lessonIds.length <= 0) {
                            continue;
                        }
                        long lessonId = lessonIds[0];
                        lessonIdList.add(lessonId);
                    }
                    if (lessonIdList.size() <= 0) {
                        return new XlsUtil.XlsErrorResult(i, j, "课程名不存在");
                    }
                    teacher.setLessonIds(Joiner.on(",").join(lessonIdList));
                    break;
            }
            return new XlsUtil.XlsErrorResult();
        });

        if (xlsErrorResult.hasError()) {
            return new Result(ResultStatus.normal_error.getStatus(), xlsErrorResult.toString());
        }

        for (Teacher teacher : teachers) {
            teacherService.add(teacher);
        }
        return new Result(ResultStatus.success.getStatus(), "");
    }
}
